<?php
/*********************************************************
author			Henson
date			2013-08-23
function		公共函数
*********************************************************/

function _getIP(){
	if(@$_SERVER["HTTP_X_FORWARDED_FOR"]){
		$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
	}elseif(@$_SERVER["HTTP_CLIENT_IP"]){
		$ip = $_SERVER["HTTP_CLIENT_IP"]; 
	}elseif(@$_SERVER["REMOTE_ADDR"]){
		$ip = $_SERVER["REMOTE_ADDR"]; 
	}elseif(getenv("HTTP_X_FORWARDED_FOR")){
		$ip = getenv("HTTP_X_FORWARDED_FOR");
	}elseif(getenv("HTTP_CLIENT_IP")){
		$ip = getenv("HTTP_CLIENT_IP");
	}elseif(getenv("REMOTE_ADDR")){
		$ip = getenv("REMOTE_ADDR");
	}else{
		$ip = "Unknown";
	}
	return $ip;
}

function _getImgWH($Img,$simgW,$simgH)
{
	$imgInfo=getimagesize($Img);
	if($imgInfo[0] == $imgInfo[1])
	{
		$imgInfo[1] = $simgH;
		$imgInfo[0] = $simgH;
	}
	if($imgInfo[0]>$imgInfo[1])
	{
		if($imgInfo[0] > $simgW)
		{
			$imgInfo[1] = floor($imgInfo[1]*($simgW/$imgInfo[0]));
			$imgInfo[0] = $simgW;
		}
	}
	else
	{
		if($imgInfo[1] > $simgH)
		{
			$imgInfo[0] = floor($imgInfo[0]*($simgH/$imgInfo[1]));
			$imgInfo[1] = $simgH;
		}
	}
	return $imgInfo;
}

function _cMkDir($dirName)
{
	if(!is_dir($dirName))
	{
		@mkdir($dirName,0777);
	}
	return true;
}

//写入文件
function _writeFile($fileBody,$writeFile,$mode="w")
{
	//打开文件清空
	$fRs = @fopen($writeFile,$mode);
	@fwrite($fRs,$fileBody);
	@fclose($fRs);
	return true;
}

//解析post字符串
function _parsePost( $method = "_POST" , $filter="" )
{
	if($method=='_POST')
		$array = $_POST;
	elseif($method=='_GET')
		$array = $_GET;
	elseif($method=='_REQUEST')
		$array = $_REQUEST;

	if(is_array($filter) && !empty($filter) )
	{
		foreach( $filter as $fk=>$fv)
		{
			unset($array[$fv]);
		}
	}elseif ($filter!="")
	{
		unset($array[$filter]);	    
	}
	
	foreach ($array as $pk=>$pv) {
		if(is_array($pv))
			foreach ($pv as $psk=>$psv) 
			{
				$s .=urlencode($pk."[]")."=".urlencode($psv)."&";
			}
		else{	
				$s .=urlencode($pk)."=".urlencode($pv)."&";
		}
	}
	return $s;
}

/**************************** upload images
example:
	$srcFile = $_FILES['upload_img'];
	$destFile = array('width'=>'200','height'=>'160','img_name'=>'cor_001','upload_path'=>'/corporation/2011-04-01/');
****************************/
function _uploadImage($srcFile=array(), $destFile=array())
{
	$allowExt = array(
		'gif'	=> array('image/gif'), 
		'jpg'	=> array('image/jpg', 'image/jpeg'), 
		'bmp'	=> array('image/bmp'), 
		'png'	=> array('image/png'), 
		'jpeg'	=> array('image/jpg', 'image/jpeg')
	);
	if (is_uploaded_file($srcFile['tmp_name']) && $srcFile['error'] == '0')
	{
		$maxwidth = @$destFile['width'];
		$maxheight = @$destFile['height'];
		
		$img_size = getimagesize($srcFile['tmp_name']);
		$width = $img_size[0];
		$height = $img_size[1];
		
		$file_info = pathinfo($srcFile["name"]); 
		$file_ext = strtolower($file_info["extension"]); 
		if(!key_exists($file_ext, $allowExt) ||  !in_array($srcFile["type"], $allowExt[$file_ext]))
		{
			return false;
		}
		
		$upload_path = $destFile['upload_path'];
		
		_cMkDir($upload_path);
		
		if (isset($destFile['img_name'])){
			$img_name = $destFile['img_name'];
			$srcFile['name'] = $img_name.'.'.$file_ext; //重命名
		}
		
		$destFile['filename'] = $upload_path.$srcFile['name']; //完整文件名

		if (($maxwidth == "" && $maxheight == "") || ($width <= $maxwidth && $height <= $maxheight))
		{
			if(move_uploaded_file($srcFile["tmp_name"],$destFile["filename"]))
			{
				return $srcFile['name'];
			}
			else
			{
				return false;
			}
		}
		else
		{
			$im = @imagecreatefromjpeg($srcFile["tmp_name"]);
			if(!$im){
				$im = @imagecreatefrompng($srcFile["tmp_name"]);
			}
			if(!$im){
				$im = @imagecreatefromgif($srcFile["tmp_name"]);
			}
			
			if($im){
				if(($maxwidth && $width > $maxwidth) || ($maxheight && $height > $maxheight)){
					if($maxwidth && $width > $maxwidth){
					$widthratio = $maxwidth/$width;
					$RESIZEWIDTH=true;
					}
					if($maxheight && $height > $maxheight){
					$heightratio = $maxheight/$height;
					$RESIZEHEIGHT=true;
					}
					if($RESIZEWIDTH && $RESIZEHEIGHT){
						if($widthratio < $heightratio){
							$ratio = $widthratio;
						}else{
							$ratio = $heightratio;
						}
					}elseif($RESIZEWIDTH){
						$ratio = $widthratio;
					}elseif($RESIZEHEIGHT){
						$ratio = $heightratio;
					}
					$newwidth = $width * $ratio;
					$newheight = $height * $ratio;
					if(function_exists("imagecopyresampled")){
						$newim = imagecreatetruecolor($newwidth, $newheight);
						imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
					}else{
						$newim = imagecreate($newwidth, $newheight);
						imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
					}
					imagejpeg($newim,$destFile['filename']);
					imagedestroy ($newim);
				}else{
					imagejpeg($im,$destFile['filename']);
				}

				imagedestroy ($im);
				return $srcFile['name'];
			}else{
				return false;
			}
		}
	}
	else
	{
		return false;
	}
}

//发送邮件
function _sendMail($mailContent = array())
{
	include_once 'PHPMailer/class.phpmailer.php';
	try {
		$mail=new PHPMailer();
		$mail->IsSMTP();
		//$mail->SMTPDebug  = true;
		$mail->SMTPAuth   = true;                  // enable SMTP authentication
		//$mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
		$mail->Host       = 'smtp.qq.com';      // sets GMAIL as the SMTP server
		$mail->Port       = '25';                   // set the SMTP port 

		$mail->Username   = "522654571@qq.com";  // GMAIL username
		$mail->Password   = "wode522@2012";            // GMAIL password

		$mail->From       = "522654571@qq.com";
		$mail->FromName   = "【reservation】";
		$mail->Subject    = $mailContent['subject'];
		$mail->Body       = $mailContent['body'];                      //HTML Body
		$mail->AltBody    = $mailContent['body']; //Text Body
		$mail->CharSet	  = "UTF-8";
		$mail->WordWrap   = 50; // set word wrap
		
		if(isset($mailContent['mailers']) && is_array($mailContent['mailers']) && count($mailContent['mailers']) > 0)
		{
			foreach ($mailContent['mailers'] as $key=>$value)
			{
				$mail->AddAddress($value['email'],$value['name']);
			}
		}
		else
		{
			$mail->AddAddress($mailContent['email'],$mailContent['name']);
		}
		
		$mail->AddReplyTo("522654571@qq.com","【reservation】");
		//$mail->AddAttachment("/path/to/file.zip");             // attachment
		//$mail->AddAttachment("/path/to/image.jpg", "new.jpg"); // attachment

		$mail->IsHTML(true); // send as HTML
		$mail->Send();
		return true;
	} catch (phpmailerException $e) {
		return false;
		//return $e->errorMessage();
	}
}

function _str2unicode($str){   
	$len = mb_strlen($str,"utf-8");
	for($i= 0;$i<$len;$i++){   
		$char = mb_substr($str,$i,1,"utf-8");
		if(!(strlen($char)>1)){   
			$dec = ord($char);   
			if($dec>16){   
				$ret .= "%".$dec;
			}else{   
				$ret .= "%".$dec;
			}
		}
		else
		{   
			$temp = base_convert(bin2hex($char),16,2);   
			$temp = substr($temp,4,4).substr($temp,10,6).substr($temp,18);   
			$ret .= "%".hexdec(strtoupper(base_convert($temp,2,16)));
		}
	}
	return	$ret;   
}
function _unicode_decode($name)
{
	// 转换编码，将Unicode编码转换成可以浏览的utf-8编码
	$pattern = '/([\w]+)|(\\\u([\w]{4}))/i';
	preg_match_all($pattern, $name, $matches);
	if (!empty($matches))
	{
		$name = '';
		for ($j = 0; $j < count($matches[0]); $j++)
		{
			$str = $matches[0][$j];
			if (strpos($str, '\\u') === 0)
			{
				$code = base_convert(substr($str, 2, 2), 16, 10);
				$code2 = base_convert(substr($str, 4), 16, 10);
				$c = chr($code).chr($code2);
				$c = iconv('UCS-2','UTF-8', $c);
				$name .= $c;
			}
			else
			{
				$name .= $str;
			}
		}
	}
	return $name;
}

//获取验证码
function _showCaptcha(){
	@ob_end_clean(); //清除之前出现的多余输入
	$captcha = new captcha();
	$captcha->generate_image();
	exit;
}
function _checkMail($email) {
	return preg_match("/^(([0-9a-zA-Z]+)|([0-9a-zA-Z]+[_.0-9a-zA-Z-]*[0-9a-zA-Z]+))@([a-zA-Z0-9-]+[.])+([a-zA-Z]{2}|net|NET|com|COM|gov|GOV|mil|MIL|org|ORG|edu|EDU|int|INT)$/", $email);
}
function _checkPassword($str)
{
	return preg_match('/^[a-zA-Z0-9]{6,30}$/',$str);
}

function  _mb_chunk_split($str,$length,$end)   
{      
    if (empty($str)) return false;   
    return chunk_split($str, $length, $end);   
}   


function _errorShow($msg)
{
	ob_start();
	if($msg == "back")
	{
		$js = "history.go(-1)";
	}
	else
	{
		$js = 'alert("'.$msg.'");history.go(-1);';
	}

	echo '<script language="javascript">
	<!--
		'. $js .'
	-->
		</script>';
	ob_end_flush();
	die;
}

function _checkLogin()
{
	global $_CFG;
	$cookie_user_id = intval($_COOKIE["uid"]);
	$cookie_user_name = $_COOKIE["username"];
	$reg_name = "#^[a-zA-Z ']{1,50}$#";
	$reg_auth = "#^[0-9a-f]{32}$#";
	$auth = $_COOKIE["auth"];
	if($cookie_user_id > 0 && preg_match($reg_name, $cookie_user_name) && preg_match($reg_auth, $auth) && md5($_CFG['secretKey'].$cookie_user_id) == $auth){
		return true;
	}else{
		return false;
	}
}

function _checkSuperLogin()
{
	global $_CFG;
	$superId = @intval($_COOKIE["r_uid"]);
	$auth = @$_COOKIE["r_auth"];
	$reg_auth = "#^[0-9a-f]{32}$#";
	if($superId > 0 && preg_match($reg_auth, $auth) && md5($_CFG['secretKey'].$superId) == $auth)
	{
		return true;
	}
	else
	{
		_showMessage("login first!", '/r_management/login.html');
		die;
	}
}

function _location($url = null){
	$location = null;
	if ( !$url) {
		$url = $_SERVER['PHP_SELF'];
	}
	elseif ( substr($url,0,1) == '?' ) {
		$url = $_SERVER['PHP_SELF'] . $url;
	}
	if ( substr($url,0,7) === 'http://' or substr($url,0,8) === 'https://' ) {
		$location = $url;
	}
	else {
		$port = null;
		if ( $_SERVER['SERVER_PORT'] == 443 ) {
			$protocol = 'https://';
		}
		elseif ( $_SERVER['SERVER_PORT']  == 80 ) {
			$protocol = 'http://';
		}
		else {
			$protocol = 'http://';
			$port = ':'. $_SERVER['SERVER_PORT'] ;
		}

		$dir = dirname($_SERVER['SCRIPT_NAME']);
		if ( $dir === "/" ) {
			$dir = "";
		}
		if ( substr($url,0,2) === './' ) {
			if ( $dir ) {
				$location = $protocol . $_SERVER['HTTP_HOST'] . $port . '/' . $dir	. '/' . basename($url);
			}
			else {
				$location = $protocol . $_SERVER['HTTP_HOST'] . $port . '/' . basename($url);
			}
		}
		elseif ( substr($url,0,1) === "/" ) {
			$location = $protocol .$_SERVER['HTTP_HOST'] . $port . $url;
		}
		else {
			$location = $protocol . $_SERVER['HTTP_HOST'] . $port . $dir . '/' . $url;
		}
	}

	header("Location: $location");
	exit();

}

function _changeEncode($str,$type='u2g'){
	if($type == 'u2g'){
		return iconv("UTF-8","gb2312//IGNORE",$str);
	}else if($type == 'letv'){
		return iconv("UTF-8","gbk",$str);
	}else{
		return iconv("gb2312","UTF-8",$str);
	}
}

function _requestToStr(){
	$arr = array();
	foreach($_POST as $key=>$value){
		if($value != ""){
			if(is_array($value) && count($value) > 0){
				foreach($value as $kk=>$vv){
					$arr[] = $key."[]=".trim($vv);
				}
			}else{
				$arr[] = $key."=".trim($value);
			}
		}
	}
	foreach($_GET as $key=>$value){
		if($value != ""){
			if(is_array($value) && count($value) > 0){
				foreach($value as $kk=>$vv){
					$arr[] = $key."[]=".trim($vv);
				}
			}else{
				$arr[] = $key."=".trim($value);
			}
		}
	}

	return implode("&",$arr);
}

function _checkCreditCard($creditCard)
{
	require_once 'Validate/FI.php';
	$valid = new Validate_FI();
	return $valid->creditCard($creditCard);
}

function strCode($string, $action = 'ENCODE')
{
    $action != 'ENCODE' && $string = base64_decode($string);
    $code = '';
    $hash = 'M#jM0NeSv#wMDG9+8rVsti80A==3g.0';
    $key = md5($hash);
    $keylen = strlen($key);
    $strlen = strlen($string);
    for ($i = 0; $i < $strlen; $i ++) 
	{
        
        $k = $i % $keylen; //余数  将字符全部位移
        $code .= $string[$i] ^ $key[$k];//位移 
    }
    return ($action != 'DECODE' ? base64_encode($code) : $code);
}

	function _showMessage($p_msg ,$p_mode)
	{
			ob_start();
			if($p_mode=="close")
				$cmd = "top.close();";
			else if($p_mode=="back")
				$cmd = "history.go(-1)";
			else
				$cmd = "location.href = '".$p_mode."';";

			echo '<script language="javascript">
			<!--
				alert("'.$p_msg.'");'.$cmd.'
			-->
				</script>';
			ob_end_flush();
			die;
	}